// 清空日志
function clearLog() {
    document.getElementById('messageLog').innerHTML = '';
}// 全局变量
let ws = null;
let gameState = null;
let myPlayerName = null;
let countdownTimer = null;
let currentBetAction = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 初始化应用
function initializeApp() {
    checkRoomStatus();
    connectWebSocket();

    // 绑定事件
    document.getElementById('totalPlayers').addEventListener('change', updateAIOptions);
    updateAIOptions(); // 初始化AI选项
}

// 检查房间状态
async function checkRoomStatus() {
    try {
        const response = await fetch('/api/room/status');
        const data = await response.json();

        if (data.success) {
            const roomData = data.data;
            console.log('房间状态:', roomData);

            // 根据房间状态显示不同界面
            if (roomData.room_state === 'waiting_for_players') {
                showRoomSetup();
            } else if (roomData.room_state === 'ready_to_start') {
                // 如果房间准备就绪但用户不在其中，显示房间设置
                showRoomSetup();
            } else {
                // 游戏进行中，显示房间设置（可能需要重新加入）
                showRoomSetup();
            }
        }
    } catch (error) {
        console.error('获取房间状态失败:', error);
        showRoomSetup();
    }
}

// 更新AI选项
function updateAIOptions() {
    const totalPlayers = parseInt(document.getElementById('totalPlayers').value);
    const aiSelect = document.getElementById('aiPlayers');

    // 清空选项
    aiSelect.innerHTML = '';

    // 添加可选的AI数量（至少留一个位置给真人）
    for (let i = 1; i < totalPlayers; i++) {
        const option = document.createElement('option');
        option.value = i;
        option.textContent = `${i}个AI`;
        if (i === Math.min(3, totalPlayers - 1)) {
            option.selected = true;
        }
        aiSelect.appendChild(option);
    }
}

// WebSocket连接
function connectWebSocket() {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/ws`;

    ws = new WebSocket(wsUrl);

    ws.onopen = function(event) {
        console.log('WebSocket连接已建立');
        updateConnectionStatus(true);
        addLogMessage('系统', 'WebSocket连接已建立');
    };

    ws.onmessage = function(event) {
        const data = JSON.parse(event.data);
        console.log('收到消息:', data);
        handleWebSocketMessage(data);
    };

    ws.onclose = function(event) {
        console.log('WebSocket连接已关闭');
        updateConnectionStatus(false);
        addLogMessage('系统', 'WebSocket连接已关闭');

        // 尝试重连
        setTimeout(connectWebSocket, 3000);
    };

    ws.onerror = function(error) {
        console.error('WebSocket错误:', error);
        updateConnectionStatus(false);
        addLogMessage('错误', 'WebSocket连接错误');
    };
}

// 更新连接状态
function updateConnectionStatus(connected) {
    const statusElement = document.getElementById('connectionStatus');
    if (connected) {
        statusElement.textContent = '已连接';
        statusElement.className = 'status-connected';
    } else {
        statusElement.textContent = '未连接';
        statusElement.className = 'status-disconnected';
    }
}

// 处理WebSocket消息
function handleWebSocketMessage(data) {
    switch (data.type) {
        case 'player_joined':
            addLogMessage('系统', `${data.data.player_name} 加入房间`);
            break;

        case 'room_state':
            handleRoomState(data.data);
            break;

        case 'game_started':
            addLogMessage('系统', '游戏开始！');
            showGameArea();
            break;

        case 'game_state':
            handleGameState(data.data);
            break;

        case 'action_required':
            handleActionRequired(data.data);
            break;

        case 'ai_action':
            handleAIAction(data.data);
            break;

        case 'showdown_result':
            handleShowdownResult(data.data);
            break;

        case 'round_end':
            handleRoundEnd(data.data);
            break;

        case 'game_end':
            handleGameEnd(data.data);
            break;

        case 'player_left':
            addLogMessage('系统', `${data.data.player_id} 离开房间`);
            break;

        case 'error':
            addLogMessage('错误', data.data.message);
            break;

        default:
            console.log('未处理的消息类型:', data.type);
    }
}

// 处理房间状态
function handleRoomState(roomData) {
    console.log('房间状态更新:', roomData);

    if (roomData.room_state === 'ready_to_start') {
        showWaitingRoom(roomData);
    } else if (roomData.room_state === 'game_in_progress') {
        showGameArea();
    }
}

// 处理游戏状态
function handleGameState(gameData) {
    console.log('游戏状态更新:', gameData);
    gameState = gameData;

    if (gameData.game_state === 'not_started') {
        return;
    }

    // 更新游戏信息
    updateGameInfo(gameData);

    // 更新公共牌
    updateCommunityCards(gameData.community_cards);

    // 更新玩家列表
    updatePlayersList(gameData.players);

    // 更新我的手牌
    updateMyHand(gameData.your_hand);

    // 更新行动按钮
    updateActionButtons(gameData);
}

// 处理行动请求
function handleActionRequired(actionData) {
    console.log('需要行动:', actionData);

    if (actionData.player_name === myPlayerName) {
        showActionPrompt(actionData);
        startCountdown(actionData.timeout);
    }
}

// 发送WebSocket消息
function sendMessage(type, data) {
    if (!ws || ws.readyState !== WebSocket.OPEN) {
        addLogMessage('错误', 'WebSocket未连接');
        return false;
    }

    const message = { type, data };
    ws.send(JSON.stringify(message));
    console.log('发送消息:', message);
    return true;
}

// 加入房间
function joinRoom() {
    const playerName = document.getElementById('playerName').value.trim();
    const totalPlayers = parseInt(document.getElementById('totalPlayers').value);
    const aiPlayers = parseInt(document.getElementById('aiPlayers').value);

    if (!playerName) {
        alert('请输入玩家名称');
        return;
    }

    myPlayerName = playerName;

    const success = sendMessage('join_room', {
        player_name: playerName,
        total_players: totalPlayers,
        ai_players: aiPlayers
    });

    if (success) {
        addLogMessage('系统', `尝试加入房间: ${playerName}`);
    }
}

// 开始游戏
function startGame() {
    const success = sendMessage('start_game', {});

    if (success) {
        addLogMessage('系统', '请求开始游戏');
    }
}

// 离开房间
function leaveRoom() {
    sendMessage('leave_room', {});
    location.reload();
}

// 玩家行动
function playerAction(action) {
    let actionData = { action: action };

    // 如果是下注或加注，需要金额
    if (action === 'bet' || action === 'raise') {
        const amount = parseInt(document.getElementById('betAmount').value);
        if (!amount || amount <= 0) {
            alert('请输入有效的下注金额');
            return;
        }
        actionData.amount = amount;
    }

    const success = sendMessage('player_action', actionData);

    if (success) {
        addLogMessage('我的行动', `${getActionText(action, actionData.amount)}`);
        hideActionPrompt();
        hideBetInput();
    }
}

// 获取行动文本
function getActionText(action, amount) {
    switch (action) {
        case 'check': return '过牌';
        case 'call': return '跟注';
        case 'bet': return `下注 ${amount}`;
        case 'raise': return `加注到 ${amount}`;
        case 'fold': return '弃牌';
        case 'all_in': return '全押';
        default: return action;
    }
}

// 显示下注输入
function showBetInput(actionType) {
    currentBetAction = actionType;

    const betInput = document.getElementById('betInput');
    const betAmount = document.getElementById('betAmount');
    const minBetHint = document.getElementById('minBetHint');

    betInput.style.display = 'block';

    if (gameState) {
        let minAmount, maxAmount;

        if (actionType === 'bet') {
            minAmount = 20; // 大盲注
            maxAmount = getCurrentPlayer()?.chips || 0;
            minBetHint.textContent = `最小下注: ${minAmount}, 最大: ${maxAmount}`;
        } else if (actionType === 'raise') {
            minAmount = gameState.min_raise;
            maxAmount = getCurrentPlayer()?.chips + getCurrentPlayer()?.current_bet || 0;
            minBetHint.textContent = `最小加注到: ${minAmount}, 最大: ${maxAmount}`;
        }

        betAmount.min = minAmount;
        betAmount.max = maxAmount;
        betAmount.value = minAmount;
    }

    betAmount.focus();
}

// 确认下注
function confirmBet() {
    if (currentBetAction) {
        playerAction(currentBetAction);
        currentBetAction = null;
    }
}

// 取消下注
function cancelBet() {
    hideBetInput();
    currentBetAction = null;
}

// 隐藏下注输入
function hideBetInput() {
    document.getElementById('betInput').style.display = 'none';
}

// 获取当前玩家信息
function getCurrentPlayer() {
    if (!gameState || !gameState.players) return null;

    return gameState.players.find(p => p.name === myPlayerName);
}

// 更新游戏信息
function updateGameInfo(gameData) {
    document.getElementById('potAmount').textContent = gameData.pot || 0;
    document.getElementById('roundName').textContent = gameData.round_name || '未知';
    document.getElementById('currentBet').textContent = gameData.current_bet || 0;
}

// 更新公共牌
function updateCommunityCards(cards) {
    const container = document.getElementById('communityCards');
    container.innerHTML = '';

    if (!cards || cards.length === 0) {
        container.innerHTML = '<div class="no-cards">暂无公共牌</div>';
        return;
    }

    cards.forEach(card => {
        const cardElement = createCardElement(card);
        container.appendChild(cardElement);
    });
}

// 更新玩家列表
function updatePlayersList(players) {
    const container = document.getElementById('playersList');
    container.innerHTML = '';

    if (!players) return;

    players.forEach(player => {
        const playerElement = createPlayerElement(player);
        container.appendChild(playerElement);
    });
}

// 更新我的手牌
function updateMyHand(cards) {
    const container = document.getElementById('myCards');
    container.innerHTML = '';

    if (!cards || cards.length === 0) {
        container.innerHTML = '<div class="no-cards">暂无手牌</div>';
        return;
    }

    cards.forEach(card => {
        const cardElement = createCardElement(card);
        container.appendChild(cardElement);
    });
}

// 创建卡牌元素
function createCardElement(card) {
    const cardDiv = document.createElement('div');
    cardDiv.className = 'card';

    // 判断花色颜色
    if (card.suit === '♥' || card.suit === '♦') {
        cardDiv.classList.add('red');
    }

    cardDiv.innerHTML = `
        <div class="card-rank">${card.rank}</div>
        <div class="card-suit">${card.suit}</div>
    `;

    return cardDiv;
}

// 创建玩家元素
function createPlayerElement(player) {
    const playerDiv = document.createElement('div');
    playerDiv.className = 'player-item';

    if (player.is_current_player) {
        playerDiv.classList.add('current-player');
    }

    if (player.folded) {
        playerDiv.classList.add('folded');
    }

    if (player.is_ai) {
        playerDiv.classList.add('ai');
    }

    const statusText = player.folded ? '已弃牌' :
                      player.all_in ? '全押' : '游戏中';

    playerDiv.innerHTML = `
        <div class="player-name">${player.name} ${player.is_ai ? '(AI)' : ''}</div>
        <div class="player-stats">
            <span class="player-chips">筹码: ${player.chips}</span>
            ${player.current_bet > 0 ? `<span class="player-bet"> | 下注: ${player.current_bet}</span>` : ''}
            <span class="player-status"> | ${statusText}</span>
        </div>
    `;

    return playerDiv;
}

// 更新行动按钮
function updateActionButtons(gameData) {
    const buttons = {
        check: document.getElementById('checkBtn'),
        call: document.getElementById('callBtn'),
        bet: document.getElementById('betBtn'),
        raise: document.getElementById('raiseBtn'),
        fold: document.getElementById('foldBtn'),
        allin: document.getElementById('allinBtn')
    };

    // 隐藏所有按钮
    Object.values(buttons).forEach(btn => btn.style.display = 'none');

    if (!gameData.your_turn || !gameData.valid_actions) {
        return;
    }

    // 显示有效行动按钮
    gameData.valid_actions.forEach(action => {
        if (buttons[action]) {
            buttons[action].style.display = 'inline-block';

            // 更新跟注按钮显示金额
            if (action === 'call' && gameData.to_call > 0) {
                document.getElementById('callAmount').textContent = gameData.to_call;
            }
        }
    });
}

// 显示行动提示
function showActionPrompt(actionData) {
    const promptDiv = document.getElementById('actionPrompt');
    const actionInfo = document.getElementById('actionInfo');

    let infoText = '轮到你行动';
    if (actionData.to_call > 0) {
        infoText += ` - 需要跟注: ${actionData.to_call}`;
    }

    actionInfo.textContent = infoText;
    promptDiv.style.display = 'block';
}

// 隐藏行动提示
function hideActionPrompt() {
    document.getElementById('actionPrompt').style.display = 'none';
    stopCountdown();
}

// 开始倒计时
function startCountdown(seconds) {
    const countdownElement = document.getElementById('countdown');
    let remaining = seconds;

    countdownTimer = setInterval(() => {
        countdownElement.textContent = remaining;

        // 最后10秒变红并闪烁
        if (remaining <= 10) {
            countdownElement.parentElement.classList.add('urgent');
        }

        remaining--;

        if (remaining < 0) {
            stopCountdown();
            hideActionPrompt();
        }
    }, 1000);
}

// 停止倒计时
function stopCountdown() {
    if (countdownTimer) {
        clearInterval(countdownTimer);
        countdownTimer = null;
    }

    const countdownElement = document.getElementById('countdown');
    countdownElement.textContent = '30';
    countdownElement.parentElement.classList.remove('urgent');
}

// 显示房间设置界面
function showRoomSetup() {
    document.getElementById('roomSetup').style.display = 'block';
    document.getElementById('waitingRoom').style.display = 'none';
    document.getElementById('gameArea').style.display = 'none';
    document.getElementById('gameEnd').style.display = 'none';
}

// 显示等待房间界面
function showWaitingRoom(roomData) {
    document.getElementById('roomSetup').style.display = 'none';
    document.getElementById('waitingRoom').style.display = 'block';
    document.getElementById('gameArea').style.display = 'none';
    document.getElementById('gameEnd').style.display = 'none';

    // 更新等待玩家列表
    const container = document.getElementById('waitingPlayers');
    container.innerHTML = '';

    if (roomData.players) {
        roomData.players.forEach(player => {
            const playerDiv = document.createElement('div');
            playerDiv.className = 'waiting-player';
            playerDiv.innerHTML = `
                <div>${player.name}</div>
                <div>${player.is_ai ? 'AI玩家' : '真人玩家'}</div>
            `;
            container.appendChild(playerDiv);
        });
    }
}

// 显示游戏区域
function showGameArea() {
    document.getElementById('roomSetup').style.display = 'none';
    document.getElementById('waitingRoom').style.display = 'none';
    document.getElementById('gameArea').style.display = 'block';
    document.getElementById('gameEnd').style.display = 'none';
}

// 显示游戏结束界面
function showGameEnd(result) {
    document.getElementById('roomSetup').style.display = 'none';
    document.getElementById('waitingRoom').style.display = 'none';
    document.getElementById('gameArea').style.display = 'none';
    document.getElementById('gameEnd').style.display = 'block';

    document.getElementById('gameResult').innerHTML = result;
}

// 添加日志消息
function addLogMessage(type, message) {
    const logContainer = document.getElementById('messageLog');
    const logEntry = document.createElement('div');
    logEntry.className = 'log-entry';

    const timestamp = new Date().toLocaleTimeString();
    logEntry.innerHTML = `
        <span class="log-timestamp">[${timestamp}]</span>
        <span class="log-type">[${type}]</span>
        <span class="log-message">${message}</span>
    `;

    logContainer.appendChild(logEntry);
    logContainer.scrollTop = logContainer.scrollHeight;
}

// 处理AI行动
function handleAIAction(actionData) {
    if (actionData.status === 'thinking') {
        addLogMessage('AI行动', `${actionData.player} 正在思考...`);
    } else {
        addLogMessage('AI行动', `${actionData.player} ${actionData.action_text}`);
    }
}

// 处理摊牌结果
function handleShowdownResult(showdownData) {
    console.log('摊牌结果:', showdownData);

    // 显示摊牌界面
    showShowdownResult(showdownData);

    // 添加日志
    if (showdownData.results) {
        showdownData.results.forEach(result => {
            if (result.type === 'single_winner') {
                addLogMessage('摊牌', `${result.winner} 获胜，赢得 ${result.amount} (${result.reason})`);
            } else if (result.type === 'showdown') {
                addLogMessage('摊牌', `摊牌开始，底池: ${result.pot}`);
                if (result.players) {
                    result.players.forEach(player => {
                        addLogMessage('摊牌', `${player.player}: ${player.hand_description}`);
                    });
                }
            }
        });
    }
}

// 处理回合结束
function handleRoundEnd(roundData) {
    addLogMessage('系统', roundData.message);

    // 显示回合结束倒计时
    if (roundData.next_round_in) {
        showRoundEndCountdown(roundData.next_round_in);
    }
}

// 处理游戏结束
function handleGameEnd(endData) {
    addLogMessage('系统', '游戏结束！');

    if (endData.winner) {
        addLogMessage('结果', `最终获胜者: ${endData.winner}`);
    }

    if (endData.message) {
        addLogMessage('结果', endData.message);
    }

    // 显示最终结果
    showGameEnd(endData);
}

// 显示摊牌结果界面
function showShowdownResult(showdownData) {
    // 创建临时的摊牌结果显示
    const existingResult = document.getElementById('showdownResult');
    if (existingResult) {
        existingResult.remove();
    }

    const resultDiv = document.createElement('div');
    resultDiv.id = 'showdownResult';
    resultDiv.className = 'showdown-result';
    resultDiv.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(0, 0, 0, 0.9);
        color: white;
        padding: 30px;
        border-radius: 15px;
        border: 3px solid #ffc107;
        z-index: 1000;
        max-width: 600px;
        text-align: center;
    `;

    let content = '<h3>🃏 摊牌结果</h3>';

    if (showdownData.community_cards) {
        content += '<div style="margin: 20px 0;"><strong>公共牌:</strong><br>';
        showdownData.community_cards.forEach(card => {
            const color = (card.suit === '♥' || card.suit === '♦') ? 'red' : 'black';
            content += `<span style="color: ${color}; font-size: 1.2em; margin: 0 5px;">${card.rank}${card.suit}</span>`;
        });
        content += '</div>';
    }

    if (showdownData.results) {
        showdownData.results.forEach(result => {
            if (result.type === 'single_winner') {
                content += `<div style="margin: 15px 0; font-size: 1.3em; color: #28a745;">
                    <strong>${result.winner} 获胜！</strong><br>
                    赢得底池: ${result.amount}<br>
                    <small>${result.reason}</small>
                </div>`;
            } else if (result.type === 'showdown' && result.players) {
                content += '<div style="margin: 20px 0;"><strong>玩家手牌:</strong></div>';
                result.players.forEach(player => {
                    content += `<div style="margin: 10px 0; padding: 10px; background: rgba(255,255,255,0.1); border-radius: 8px;">
                        <strong>${player.player}</strong><br>`;

                    if (player.hand) {
                        player.hand.forEach(card => {
                            const color = (card.suit === '♥' || card.suit === '♦') ? 'red' : 'black';
                            content += `<span style="color: ${color}; font-size: 1.1em; margin: 0 3px;">${card.rank}${card.suit}</span>`;
                        });
                        content += '<br>';
                    }

                    content += `<span style="color: #ffc107;">${player.hand_description}</span>
                    </div>`;
                });
            }
        });
    }

    content += '<div style="margin-top: 20px;"><button onclick="closeShowdownResult()" style="padding: 10px 20px; font-size: 16px;">确定</button></div>';

    resultDiv.innerHTML = content;
    document.body.appendChild(resultDiv);

    // 5秒后自动关闭
    setTimeout(closeShowdownResult, 5000);
}

// 关闭摊牌结果
function closeShowdownResult() {
    const resultDiv = document.getElementById('showdownResult');
    if (resultDiv) {
        resultDiv.remove();
    }
}

// 显示回合结束倒计时
function showRoundEndCountdown(seconds) {
    const existingCountdown = document.getElementById('roundEndCountdown');
    if (existingCountdown) {
        existingCountdown.remove();
    }

    const countdownDiv = document.createElement('div');
    countdownDiv.id = 'roundEndCountdown';
    countdownDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: rgba(255, 193, 7, 0.9);
        color: #333;
        padding: 15px;
        border-radius: 10px;
        font-weight: bold;
        z-index: 999;
    `;

    let remaining = seconds;
    countdownDiv.textContent = `下一轮开始: ${remaining}秒`;
    document.body.appendChild(countdownDiv);

    const timer = setInterval(() => {
        remaining--;
        if (remaining > 0) {
            countdownDiv.textContent = `下一轮开始: ${remaining}秒`;
        } else {
            clearInterval(timer);
            countdownDiv.remove();
        }
    }, 1000);
}